package ai.application;

import java.util.ArrayList;

import ai.agents.Agent;
import ai.gui.Gui;
import ai.lights.Lightable;
import ai.spatial.Vector;

public class Simulation {
	private Gui gui;
	private Environment environment;
	private ArrayList<Agent> agents;
	private ArrayList<Lightable> lights;
	
	public Simulation(Gui gui, Environment environment){
		this.gui = gui;
		this.environment = environment;
		agents = new ArrayList<Agent>();
		lights = new ArrayList<Lightable>();
	}
	
	public void addAgent(Agent agent, Vector position){
		agent.setPosition(adjustPosition(position));
		this.agents.add(agent);
	}
	
	public void addShinyAgent(Agent agent, Vector position)
	{
		agent.setPosition(adjustPosition(position));
		this.agents.add(agent);
		this.lights.add(agent);
	}
	
	public Vector adjustPosition(Vector position){
		double x;
		if(position.getX() > this.environment.getMaxX()){
			x = this.environment.getMaxX();
		}
		else if(position.getX() < this.environment.getMinX()){
			x = this.environment.getMinX();
		}
		else{
			x = position.getX();
		}
		
		double y;
		if(position.getY() > this.environment.getMaxY()){
			y = this.environment.getMaxY();
		}
		else if(position.getY() < this.environment.getMinY()){
			y = this.environment.getMinY();
		}
		else{
			y = position.getY();
		}
		return new Vector(x,y);
	}
	
	public void run() {
		
		double time = 0;
		while (time < Config.getStopTime()) {
			doSimulationStep(time);
			time += Config.getSimStepSize();;
		}
		
		
	}

	private void doSimulationStep(double time) {
		updateAgents();
		moveAgents();
		updateGui();
	}
	
	private void moveAgents() {
		for (Agent agent : this.agents) {
			this.environment.moveAgent(agent);
		}
	}

	private void updateGui() {
		if (this.gui != null) {
			this.gui.update(this.agents, this.lights);
		}
	}
	
	private void updateAgents() {
		for(Agent agent : this.agents){
			agent.update(environment, lights);
		}		
	}

	public void addLight(Lightable light, Vector position) {
		light.setPosition(adjustPosition(position));
		this.lights.add(light);
	}

}
